package com.example.project7.utils;

import android.util.Log;

import com.example.project7.model.ApiError;
import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {
    private static final String TAG = "HttpUtil";
    private static final Gson gson = new Gson();

    /**
     * 发送POST请求
     *
     * @param urlString 请求地址
     * @param requestBody 请求体对象
     * @param responseClass 响应类类型
     * @param <T> 响应类型
     * @return ApiResponse对象，包含响应数据或错误信息
     */
    public static <T> ApiResponse<T> post(String urlString, Object requestBody, Class<T> responseClass) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            
            // 设置请求方法和属性
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            
            // 发送请求体
            String jsonBody = gson.toJson(requestBody);
            Log.d(TAG, "Sending POST request to: " + urlString);
            Log.d(TAG, "Request body: " + jsonBody);
            
            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
            dos.writeBytes(jsonBody);
            dos.flush();
            dos.close();
            
            // 获取响应码
            int responseCode = connection.getResponseCode();
            Log.d(TAG, "Response code: " + responseCode);
            
            // 读取响应
            InputStream inputStream;
            if (responseCode >= 200 && responseCode < 300) {
                inputStream = connection.getInputStream();
            } else {
                inputStream = connection.getErrorStream();
            }
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            
            String responseString = response.toString();
            Log.d(TAG, "Response body: " + responseString);
            
            if (responseCode >= 200 && responseCode < 300) {
                // 成功响应
                T responseData = gson.fromJson(responseString, responseClass);
                return new ApiResponse<>(true, responseData, null);
            } else {
                // 错误响应
                ApiError error = gson.fromJson(responseString, ApiError.class);
                return new ApiResponse<>(false, null, error.getError());
            }
        } catch (Exception e) {
            Log.e(TAG, "Error occurred during POST request", e);
            return new ApiResponse<>(false, null, "网络请求失败: " + e.getMessage());
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * 发送GET请求
     *
     * @param urlString 请求地址
     * @param token 认证Token
     * @param responseClass 响应类类型
     * @param <T> 响应类型
     * @return ApiResponse对象，包含响应数据或错误信息
     */
    public static <T> ApiResponse<T> get(String urlString, String token, Class<T> responseClass) {
        HttpURLConnection connection = null;
        try {
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            
            // 设置请求方法和属性
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Accept", "application/json");
            if (token != null && !token.isEmpty()) {
                connection.setRequestProperty("Authorization", "Bearer " + token);
            }
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            
            Log.d(TAG, "Sending GET request to: " + urlString);
            
            // 获取响应码
            int responseCode = connection.getResponseCode();
            Log.d(TAG, "Response code: " + responseCode);
            
            // 读取响应
            InputStream inputStream;
            if (responseCode >= 200 && responseCode < 300) {
                inputStream = connection.getInputStream();
            } else {
                inputStream = connection.getErrorStream();
            }
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();
            
            String responseString = response.toString();
            Log.d(TAG, "Response body: " + responseString);
            
            if (responseCode >= 200 && responseCode < 300) {
                // 成功响应
                T responseData = gson.fromJson(responseString, responseClass);
                return new ApiResponse<>(true, responseData, null);
            } else {
                // 错误响应
                ApiError error = gson.fromJson(responseString, ApiError.class);
                return new ApiResponse<>(false, null, error.getError());
            }
        } catch (Exception e) {
            Log.e(TAG, "Error occurred during GET request", e);
            return new ApiResponse<>(false, null, "网络请求失败: " + e.getMessage());
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}